<?php

namespace app\cardeadmin\controller;

use app\api\controller\PublicApi;
use app\common\controller\AdminController;
use app\common\model\CardsLog;
use app\common\model\CardsTrans;
use app\common\model\CardsTransactions;
use app\common\model\FundCard;
use app\common\model\FundCheck;
use app\common\model\LssFundUser;
use app\common\model\ManageFundLog;
use app\common\model\UserBank;
use app\common\model\UserCashLog;
use app\common\model\UserHtPay;
use app\common\model\UserPay;
use app\common\model\UserPocPay;
use think\facade\Db;
use think\facade\View;
use app\common\model\FundSource;
use app\api\controller\Index;
use think\facade\Cache;

/**
 * 余额管理
 * Class ArticleType
 * @package app\manage\controller
 */
class Balance extends AdminController
{
    public function fundsApi()
    {
        if($this->request->isAjax()){
            $headerType         = 'Comdata';
            $param      = [
                "user_id"           => 0,
                "action_type"       => "search_funds",
                "card_type"         => "556305",
                "post_param"  => []
            ];
            $send_api= PublicApi::requestApi($headerType,$param);
            $return_blog    = $send_api['blog'];
            $return_list    = $send_api['list'];
            $result = [
                'code'  => 0,
                'msg'   => lang('get info success'),
                'data'  => [],
                'count' => 1,
            ];
            if($return_blog){
                $result['data'] = $return_list;
            }
            return $result;
        }
        return View::fetch();
    }

    public function fundCard()
    {
        if($this->request->isAjax()){
            $fcModel = new FundCard();
            return $fcModel->tableDataAdmin(input('param.'));
        }
        return View::fetch();
    }

    public function pockyt()
    {
        if ($this->request->isAjax()) {
            $logModel = new UserPocPay();
            $request = input('param.');
            return $logModel->tableDataAdmin($request);
        }
        return  View::fetch();
    }

    public function htpay()
    {
        if ($this->request->isAjax()) {
            $logModel = new UserHtPay();
            $request = input('param.');
            return $logModel->tableDataAdmin($request);
        }
        return  View::fetch();
    }

    public function createCard()
    {
        $type_amount = input('post.type_amount');
        $blog        = false;
        $j           = 0;
        $fund_card_id= Db::name('fund_card')->order('id desc')->limit(1)->value('id');
        for($i=$fund_card_id;$i<($fund_card_id+50);$i++){
            $ctime        = getUtcTime();
            $random_value = getRandomString(10);
            $value        = 'VDC' . md5(date('YmdHis') . $i . $random_value);
            $pwd          = md5($value . $ctime . 'vvcard2023');
            $re = Db::name('fund_card')->save([
                'value'  => $value,
                'pwd'    => $pwd,
                'amount' => ($type_amount==1)? 100.00:50.00,
                'ctime'  => $ctime
            ]);
            if($re){
                $j++;
                $blog         = true;
            }else{
                break;
            }
        }
        if($blog){
            return $this->scs("成功生成 {$j} 张.");
        }else{
            return $this->err("生成失败,且只成功 {$j} 张");
        }
    }

    public function fundsApiTwo()
    {
        if($this->request->isAjax()){
            $headerType         = 'Comdata';
            $param      = [
                "user_id"           => 0,
                "action_type"       => "search_funds",
                "card_type"         => "556766",
                "post_param"  => []
            ];
            $send_api= PublicApi::requestApi($headerType,$param);
            $return_blog    = $send_api['blog'];
            $return_list    = $send_api['list'];
            $result = [
                'code'  => 0,
                'msg'   => lang('get info success'),
                'data'  => [],
                'count' => 1,
            ];
            if($return_blog){
                $result['data'] = $return_list;
            }
            return $result;
        }
        return View::fetch();
    }

    public function fundsApiThree()
    {
        if($this->request->isAjax()){
            $headerType         = 'Comdata';
            $param      = [
                "user_id"           => 0,
                "action_type"       => "search_funds",
                "card_type"         => "556766",
                "bank_type"         => 2,
                "post_param"  => []
            ];
            $send_api= PublicApi::requestApi($headerType,$param);
            $return_blog    = $send_api['blog'];
            $return_list    = $send_api['list'];
            $result = [
                'code'  => 0,
                'msg'   => lang('get info success'),
                'data'  => [],
                'count' => 1,
            ];
            if($return_blog){
                $result['data'] = $return_list;
            }
            return $result;
        }
        return View::fetch();
    }

    public function lssFundLog()
    {
        if($this->request->isAjax()){
            $fcModel = new LssFundUser();
            return $fcModel->tableDataAdmin(input('param.'));
        }
        return View::fetch();
    }


    public function accountApi()
    {
        if($this->request->isAjax()){
            $fcModel = new UserBank();
            return $fcModel->tableDataAdmin(input('param.'));
        }
        return View::fetch();
    }

    public function upBankAccount()
    {
        $ctime  = getUtcTime();
        $send_api_919   = $this->getAccountData('556305' , 1);
        $list   = [];
        if($send_api_919['blog']){
            $list += [
                'user_919'      => $send_api_919['list']['accountCode'],
                'amount_919'    => $send_api_919['list']['accountBalance']
            ];
        }
        $send_api_616   = $this->getAccountData('556766' , 1);
        if($send_api_616['blog']){
            $list += [
                'user_616'      => $send_api_616['list']['accountCode'],
                'amount_616'    => $send_api_616['list']['accountBalance'],
            ];
        }
        $send_api_75J   = $this->getAccountData('556766' , 2);
        if($send_api_75J['blog']){
            $list += [
                'user_75J'      => $send_api_75J['list']['accountCode'],
                'amount_75J'    => $send_api_75J['list']['accountBalance'],
            ];
        }
        $bank_3_param   = [
            "action_type"   => "get_account_token",
        ];
        $bank_3_list    = PublicApi::requestApi('Connexpay',$bank_3_param);
        if($bank_3_list['blog']){
            $list += [
                'user_lss'      => "Connexpay",
                'amount_lss'    => $bank_3_list['list']['totalATA'],
            ];
        }

        $list += ['ctime'     => $ctime];
        $blog = Db::name('user_bank')->save($list);
        if($blog){
            return $this->scs('up success');
        }else{
            return $this->err('up error');
        }
    }

    public function getAccountData($card_type , $bank_type)
    {
        $headerType         = 'Comdata';
        $param      = [
            "user_id"           => 0,
            "action_type"       => "search_account",
            "card_type"         => $card_type,
            "bank_type"         => $bank_type,
            "post_param"        => []
        ];
        $send_api= PublicApi::requestApi($headerType,$param);
        return $send_api;

    }
    /**
     * 余额列表
     * @author 救火队队长
     */
    public function index()
    {
        if($this->request->isAjax()){
            $data = input('param.');
            $cdModel = new FundSource();
            return $cdModel->tableDataAdmin($data);
        }
        return View::fetch();
    }

    public function sourceAdd()
    {
        if($this->request->isPost()) {
            $data = input('param.');
            $model = new FundSource();
            $re = $model->fundEdit('add' , $data);
            if($re){
                return $this->scs('add success');
            }else{
                return $this->err('add error');
            }
        }
        return View::fetch();
    }

    public function sourceEdit()
    {
        $model = new FundSource();
        if($this->request->isPost()) {
            $data = input('param.');
            $model = new FundSource();
            $re = $model->fundEdit('edit' , $data);
            if($re){
                return $this->scs('edit success');
            }else{
                return $this->err('edit error');
            }
        }
        $id = input('get.id');
        View::assign('data',$model->find($id));
        return View::fetch();
    }

    public function sourceDel()
    {
        $id = input('post.id');
        $model = new FundSource();
        $re = $model->fundEdit('del' , ['id' => $id]);
        if($re){
            return $this->scs('del success');
        }else{
            return $this->err('del error');
        }
    }

    /**
     * Funding Activity
     * @return array|mixed|string
     * @throws \think\db\exception\DbException
     */
    public function funding()
    {
        if($this->request->isAjax()){
            $fcModel = new FundCheck();
            return $fcModel->tableDataAdmin(input('param.') , 0);
        }
        return View::fetch();
    }

    public function fundingDeb()
    {
        if($this->request->isAjax()){
            $fcModel = new FundCheck();
            return $fcModel->tableDataAdmin(input('param.') , 1);
        }
        return View::fetch();
    }

    public function fundsEdit()
    {
        $fcModel = new FundCheck();
        if($this->request->isPost()) {
            $data = input('param.');
            if(!isset($data['check_status'])) return $this->err('Please Check the Status.');
            if(!check_param($data['amount'],'zs_two')) return $this->err('The amount format is incorrect.');
            $redis_manage_action = Cache::store('redis')->get('manage_action_user_balance');
            if (!$redis_manage_action) {
                $re = $fcModel->fundEdit($data + ['manage_id' => $this->manage_id]);
                if($re){
                    return $this->scs('edit success');
                }else{
                    return $this->err('edit error');
                }
            }else{
                return $this->err('有未处理的充值确认,请稍后.');
            }
        }

        $fc_id          = input('get.fc_id');
        $fc_list        = $fcModel->find($fc_id);
        $user_id        = $fc_list['user_id'];
        $pay_type       = $fc_list['pay_type'];
        $check_num      = $fc_list['check_num'];
        $check_status   = $fc_list['check_status'];
        $remark         = $fc_list['remark'];
        $manage_remark  = $fc_list['msg'];

        $user_list      = Db::name('user')->find($user_id);
        $user_num       = $user_list['user_num'];

        //通过第一个字母判断读取哪张表
        $table_name = '';
        switch ($pay_type){
            case 1:
                $table_name = 'fund_check_alipay';
                break;
            case 2:
                $table_name = 'fund_check_wechat';
                break;
        }
        $detail_list= Db::name($table_name)->where(['check_num'=>$check_num])->find();
        View::assign([
            'check_status'  => $check_status,
            'remark'        => $remark,
            'data'          => $detail_list,
            'fc_id'         => $fc_id,
            'pay_type'     => ($pay_type == 1)?'支付宝':'微信',
            'user_num'      => $user_num,
            'manage_remark' => $manage_remark
        ]);
        return View::fetch();
    }


    public function fundsRemark()
    {
        if($this->request->isPost()) {
            $data           = input('param.');
            $fund_id        = $data['fund_id'];
            $remark         = $data['remark'];
            $fcModel        = new FundCheck();
            $re = $fcModel->where(['id'=>$fund_id])->update(['msg'=>$remark]);

            if($re){
                return $this->scs('Confirm the successful.');
            }else{
                return $this->scs('Confirm the failed.');
            }
        }

        $id     = input('get.id');
        $fcModel = new FundCheck();
        $list = $fcModel->find($id);

        View::assign([
            'remark'    => $list['msg'],
            'fund_id'   => $id,
        ]);
        View::layout(false);
        return [
            'status'    => 1,
            'datas'     => View::fetch()
        ];
    }


    /**
     * Account Activity
     * @return array|mixed|string
     * @throws \think\db\exception\DbException
     */
    public function account()
    {
        if($this->request->isAjax()){
            $model = new UserCashLog();
            return $model->tableDataAdmin(input('param.'));
        }
        $card_num = input('get.card_num' , '');
        $desc     = '';
        if(!empty($card_num)){
            $desc = '退款服务费 (**** ' . substr($card_num , -4). ')';
        }
        View::assign([
            'desc'    => $desc
        ]);
        return View::fetch();
    }

    /**
     * Account Activity
     * @return array|mixed|string
     * @throws \think\db\exception\DbException
     */
    public function manage()
    {
        if($this->request->isAjax()){
            $model = new ManageFundLog();
            return $model->tableDataAdmin(input('param.'));
        }
        return View::fetch();
    }

    /**
     * Card Transactions
     * @return array|mixed|string
     * @throws \think\db\exception\DbException
     */
    public function cardLog()
    {
        if($this->request->isAjax()){
            $model = new CardsLog();
            return $model->tableDataAdmin(input('param.'));
        }
        return View::fetch();
    }

    /**
     * Card Transactions
     * @return array|mixed|string
     * @throws \think\db\exception\DbException
     */
    public function cardPay()
    {
        if($this->request->isAjax()){
            $model = new CardsTrans();
            return $model->tableDataAdmin(input('param.'));
        }
        return View::fetch();
    }

    public function maReserve()
    {
        if($this->request->isAjax()){
            $list = CardsTrans::getTotalDeposit();
            return $result = [
                'code'  => 0,
                'msg'   => lang('get info success'),
                'data'  => $list['data'],
                'count' => $list['count'],
            ];
        }
        return View::fetch();
    }

}